package com.it.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.it.entity.*;
import com.it.mapper.*;
import com.it.service.OrderService;
import com.it.util.DateUtil;
import com.it.util.ItdragonUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {
    @Resource
    private ItdragonUtils itdragonUtils;
    @Resource
    private OrderFromMapper orderFromMapper;
    @Resource
    private TrolleyMapper trolleyMapper;
    @Resource
    private OrderDetailsMapper orderDetailsMapper;
    @Resource
    private LogisticsMapper logisticsMapper;
    @Resource
    private EvaluateMapper evaluateMapper;
    @Resource
    private SalesReturnMapper salesReturnMapper;
    @Resource
    private ProductMapper productMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private InventoryMapper inventoryMapper;

    @Override
    public Page<OrderFrom> selectPage(OrderFrom orderFrom, int page, int limit) {
        EntityWrapper<OrderFrom> searchInfo = new EntityWrapper<>();
        Page<OrderFrom> pageInfo = new Page<>(page, limit);
        if (ItdragonUtils.stringIsNotBlack(orderFrom.getUserId())) {
            searchInfo.eq("userId", orderFrom.getUserId());
        }
        if (ItdragonUtils.stringIsNotBlack(orderFrom.getStatus())) {
            searchInfo.eq("status", orderFrom.getStatus());
        }
        if ("退货中".equals(orderFrom.getStatus())) {
            searchInfo.or().eq("status", "退货成功");
        }
        if (ItdragonUtils.stringIsNotBlack(orderFrom.getUuId())) {
            searchInfo.eq("uuId", orderFrom.getUuId());
        }
        List<OrderFrom> resultList = orderFromMapper.selectPage(pageInfo, searchInfo);
        if (!resultList.isEmpty()) {
            pageInfo.setRecords(resultList);
        }
        return pageInfo;
    }

    @Override
    public List<OrderDetails> selectPage(OrderDetails orderDetails) {
        EntityWrapper<OrderDetails> searchInfo = new EntityWrapper<>();
        if (ItdragonUtils.stringIsNotBlack(orderDetails.getOrderId())) {
            searchInfo.eq("orderId", orderDetails.getOrderId());
        }
        List<OrderDetails> orderDetailsList = orderDetailsMapper.selectList(searchInfo);
        return orderDetailsList;
    }

    @Override
    public boolean insert(OrderFrom orderFrom) {
        Integer insert = orderFromMapper.insert(orderFrom);
        if (insert > 0) {
            return true;
        }
        return false;
    }

    @Override
    public boolean delById(String id) {
        //删除订单的同时删除订单详情
        EntityWrapper<OrderDetails> wapperOrderDetails = new EntityWrapper<>();
        wapperOrderDetails.eq("orderId", id);
        orderDetailsMapper.delete(wapperOrderDetails);
        //删除订单的同时删除相应的物流信息
        EntityWrapper<Logistics> wapperOrderLogistics = new EntityWrapper<>();
        wapperOrderLogistics.eq("orderId", id);
        logisticsMapper.delete(wapperOrderLogistics);
        Integer delete = orderFromMapper.deleteById(id);
        if (delete > 0) {
            return true;
        }
        return false;
    }

    @Override
    public boolean delTolleyById(String id) {
        Integer delete = trolleyMapper.deleteById(id);
        if (delete > 0) {
            return true;
        }
        return false;
    }

    @Override
    public boolean edit(OrderFrom orderFrom) {
        Integer update = orderFromMapper.updateById(orderFrom);
        if (update > 0) {
            return true;
        }
        return false;
    }

    @Override
    public boolean settle(String ids, String nums, Float price, Address address, String mode, String content) {
        //首先生成订单
        OrderFrom orderFrom = new OrderFrom();
        orderFrom.setStatus("未付款");
        orderFrom.setMode(mode);
        orderFrom.setContent(content);
        orderFrom.setTime(DateUtil.getNowDateSS());
        orderFrom.setUserId(itdragonUtils.getSessionUser().getId());
        orderFrom.setPrice(price);
        orderFrom.setUuId(itdragonUtils.getOrderIdByUUId());
        //获取默认地址
        orderFrom.setAddress("地址:" + address.getCityPicker() + address.getDetailAddress() + "  " + address.getConsignee() + " " + address.getPhone());
        Integer insert = orderFromMapper.insert(orderFrom);
        if (insert > 0) {
            //如果订单生成成功则生成订单详情
            String[] split = ids.split(",");
            String[] split1 = nums.split(",");
            boolean flag = false;
            for (int i = 0; i < split.length; i++) {
                //通过购物车id查询信息
                Trolley trolley = trolleyMapper.selectById(split[i]);
                OrderDetails orderDetails = new OrderDetails();
                orderDetails.setOrderId(orderFrom.getId());
                orderDetails.setProductImg(trolley.getProductImg());
                orderDetails.setProductName(trolley.getProductName());
                orderDetails.setProductParam(trolley.getProductParam());
                orderDetails.setStatus("0");
                orderDetails.setProductPrice(trolley.getProductPrice());
                orderDetails.setProductId(trolley.getProductId());
                orderDetails.setProductNum(Integer.valueOf(split1[i]));
                Integer insert1 = orderDetailsMapper.insert(orderDetails);
                if (insert1 > 0) {
                    //如果生成成功,删除这个id下的购物车信息
                    Integer integer = trolleyMapper.deleteById(split[i]);
                    if (integer > 0) {
                        flag = true;
                    }
                } else {
                    flag = false;
                }
            }
            return flag;
        } else {
            return false;
        }
    }

    @Override
    public boolean sale(String productId, String number, Address address, String mode, String content) {
        Product product = productMapper.selectById(productId);
        //首先生成订单
        OrderFrom orderFrom = new OrderFrom();
        orderFrom.setStatus("未付款");
        orderFrom.setMode(mode);
        orderFrom.setContent(content);
        orderFrom.setTime(DateUtil.getNowDateSS());
        orderFrom.setUserId(itdragonUtils.getSessionUser().getId());
        if ("1".equals(userMapper.selectById(itdragonUtils.getSessionUser().getId()).getUserRank())) {
            orderFrom.setPrice(product.getPrice() * product.getDiscount() * Float.valueOf(number));
        } else {
            orderFrom.setPrice(product.getPrice() * Float.valueOf(number));
        }
        orderFrom.setUuId(itdragonUtils.getOrderIdByUUId());
        //获取默认地址
        orderFrom.setAddress("地址:" + address.getCityPicker() + address.getDetailAddress() + "  " + address.getConsignee() + " " + address.getPhone());
        Integer insert = orderFromMapper.insert(orderFrom);
        if (insert > 0) {
            //如果订单生成成功则生成订单详情
            OrderDetails orderDetails = new OrderDetails();
            orderDetails.setOrderId(orderFrom.getId());
            orderDetails.setProductImg(product.getImg());
            orderDetails.setProductName(product.getName());
            orderDetails.setProductParam(product.getParameter());
            orderDetails.setStatus("0");
            orderDetails.setProductPrice(product.getPrice());
            orderDetails.setProductId(product.getId());
            orderDetails.setProductNum(Integer.valueOf(number));
            Integer insert1 = orderDetailsMapper.insert(orderDetails);
            if (insert1 > 0) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    @Override
    public boolean sale(String productId, String number, String address, String mode, String content) {
        Product product = productMapper.selectById(productId);
        //首先生成订单
        OrderFrom orderFrom = new OrderFrom();
        orderFrom.setStatus("已付款");
        orderFrom.setMode(mode);
        orderFrom.setContent(content);
        orderFrom.setTime(DateUtil.getNowDateSS());
        orderFrom.setUserId(itdragonUtils.getSessionUser().getId());
        if ("1".equals(userMapper.selectById(itdragonUtils.getSessionUser().getId()).getUserRank())) {
            orderFrom.setPrice(product.getPrice() * product.getDiscount() * Float.valueOf(number));
        } else {
            orderFrom.setPrice(product.getPrice() * Float.valueOf(number));
        }
        orderFrom.setUuId(itdragonUtils.getOrderIdByUUId());
        //获取默认地址
        orderFrom.setAddress(address);
        Integer insert = orderFromMapper.insert(orderFrom);
        if (insert > 0) {
            //如果订单生成成功则生成订单详情
            OrderDetails orderDetails = new OrderDetails();
            orderDetails.setOrderId(orderFrom.getId());
            orderDetails.setProductImg(product.getImg());
            orderDetails.setProductName(product.getName());
            orderDetails.setProductParam(product.getParameter());
            orderDetails.setStatus("0");
            orderDetails.setProductPrice(product.getPrice());
            orderDetails.setProductId(product.getId());
            orderDetails.setProductNum(Integer.valueOf(number));
            Integer insert1 = orderDetailsMapper.insert(orderDetails);
            if (insert1 > 0) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }

    }

    @Override
    public boolean toPay(String id) {
        //首先将订单详情的状态修改
        OrderDetails orderDetails = new OrderDetails();
        orderDetails.setStatus("1");
        EntityWrapper<OrderDetails> wrapper = new EntityWrapper<>();
        wrapper.eq("orderId", id);
        Integer update = orderDetailsMapper.update(orderDetails, wrapper);
        if (update > 0) {
            //修改订单的状态
            OrderFrom orderFrom = new OrderFrom();
            orderFrom.setStatus("待发货");
            orderFrom.setId(id);
            orderFromMapper.updateById(orderFrom);
            return true;
        }
        return false;

    }

    @Override
    public boolean remind(String orderId) {
        Logistics logistics = new Logistics();
        logistics.setOrderId(orderId);
        logistics.setTime(DateUtil.getNowDateSS());
        logistics.setContent("用户提醒发货");
        logistics.setType("remind");
        Integer insert = logisticsMapper.insert(logistics);
        if (insert > 0) {
            return true;
        }
        return false;
    }

    @Override
    public List<Logistics> getRemind(String orderId, String type) {
        EntityWrapper<Logistics> wrapper = new EntityWrapper<>();
        wrapper.eq("orderId", orderId);
        wrapper.eq("type", type);
        List<Logistics> logisticsList = logisticsMapper.selectList(wrapper);
        return logisticsList;
    }

    @Override
    public boolean deleteRemind(String orderId) {
        EntityWrapper<Logistics> wrapper = new EntityWrapper<>();
        wrapper.eq("orderId", orderId);
        wrapper.eq("type", "remind");
        Integer delete = logisticsMapper.delete(wrapper);
        if (delete > 0) {
            return true;
        }
        return false;
    }

    @Override
    public boolean addLogistics(String orderId, String content) {
        Logistics logistics = new Logistics();
        logistics.setOrderId(orderId);
        logistics.setContent(content);
        logistics.setTime(DateUtil.getNowDateSS());
        logistics.setType("logistics");
        Integer insert = logisticsMapper.insert(logistics);
        if (insert > 0) {
            return true;
        }
        return false;
    }

    @Override
    public boolean addEvaluate(String orderId, String content, String score) {
        //首先修改订单的状态
        OrderFrom orderFrom = new OrderFrom();
        orderFrom.setId(orderId);
        orderFrom.setStatus("交易完成");
        Integer integer = orderFromMapper.updateById(orderFrom);
        if (integer > 0) {
            //用户
            User user = itdragonUtils.getSessionUser();
            //时间
            String nowDateSS = DateUtil.getNowDateSS();
            //查询出订单下所有的商品id
            EntityWrapper<OrderDetails> wrapper = new EntityWrapper<>();
            wrapper.eq("orderId", orderId);
            List<OrderDetails> orderDetailList = orderDetailsMapper.selectList(wrapper);
            boolean falg = false;
            for (OrderDetails orderDetails : orderDetailList) {
                //添加评价信息
                Evaluate evaluate = new Evaluate();
                evaluate.setContent(content);
                evaluate.setScore(score);
                evaluate.setProductId(orderDetails.getProductId());
                evaluate.setTime(nowDateSS);
                evaluate.setImg(user.getImgUrl());
                evaluate.setUserName(user.getUserName());
                Integer insert = evaluateMapper.insert(evaluate);
                if (insert > 0) {
                    falg = true;
                } else {
                    falg = false;
                }
            }
            return falg;
        }
        return false;
    }

    @Override
    public Float favorable(String productId) {
        //查询商品所有评价
        EntityWrapper<Evaluate> wrapper = new EntityWrapper<>();
        wrapper.eq("productId", productId);
        List<Evaluate> evaluates = evaluateMapper.selectList(wrapper);
        if (evaluates.isEmpty()) {
            return Float.valueOf(0);
        } else {
            Float good = Float.valueOf(0);
            for (Evaluate evaluate : evaluates) {
                if (Float.valueOf(evaluate.getScore()) >= Float.valueOf(3)) {
                    good = good + Float.valueOf(1);
                }
            }
            DecimalFormat df = new DecimalFormat("#.00");
            Float value = Float.valueOf(df.format(good / evaluates.size()));
            return value * 100;
        }

    }

    @Override
    public boolean salesReturn(String orderId, String content) {
        //先改变订单状态
        //首先修改订单的状态
        OrderFrom orderFrom = new OrderFrom();
        orderFrom.setId(orderId);
        orderFrom.setStatus("退货中");
        Integer integer = orderFromMapper.updateById(orderFrom);
        OrderFrom orderFrom1 = orderFromMapper.selectById(orderId);
        if (integer > 0) {
            //新增退款信息
            SalesReturn salesReturn = new SalesReturn();
            salesReturn.setOrderId(orderId);
            salesReturn.setReason(content);
            salesReturn.setOrderUuId(orderFrom1.getUuId());
            salesReturn.setTime(DateUtil.getNowDateSS());
            salesReturn.setUserName(itdragonUtils.getSessionUser().getUserName());
            Integer insert = salesReturnMapper.insert(salesReturn);
            if (insert > 0) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    @Override
    public Page<SalesReturn> selectPage(SalesReturn salesReturn, int page, int limit) {
        EntityWrapper<SalesReturn> searchInfo = new EntityWrapper<>();
        Page<SalesReturn> pageInfo = new Page<>(page, limit);
        if (ItdragonUtils.stringIsNotBlack(salesReturn.getOrderUuId())) {
            searchInfo.eq("orderUuId", salesReturn.getOrderUuId());
        }
        List<SalesReturn> resultList = salesReturnMapper.selectPage(pageInfo, searchInfo);
        if (!resultList.isEmpty()) {
            pageInfo.setRecords(resultList);
        }
        return pageInfo;
    }

    @Override
    public boolean delSalesById(String id, String orderId) {
        //先将订单状态改为退货成功
        OrderFrom orderFrom = new OrderFrom();
        orderFrom.setId(orderId);
        orderFrom.setStatus("退货成功");
        Integer integer = orderFromMapper.updateById(orderFrom);
        Integer delete = salesReturnMapper.deleteById(id);
        if (delete > 0) {
            return true;
        }
        return false;

    }

    @Override
    public List<Evaluate> getEvaluateList(String productId) {
        EntityWrapper<Evaluate> wrapper = new EntityWrapper<>();
        wrapper.eq("productId", productId);
        List<Evaluate> evaluateList = evaluateMapper.selectList(wrapper);
        return evaluateList;
    }

    @Override
    public Product getProductBytrolleyId(String id) {
        Trolley trolley = trolleyMapper.selectById(id);
        Product product = productMapper.selectById(trolley.getProductId());
        return product;
    }

    @Override
    public OrderFrom getOrderFrom(String id) {
        return orderFromMapper.selectById(id);

    }

    @Override
    public List<OrderDetails> getOrderDetailsByProductId(String productId) {
        EntityWrapper<OrderDetails> wrapper = new EntityWrapper<>();
        wrapper.eq("productId", productId);
        List<OrderDetails> orderDetailsList = orderDetailsMapper.selectList(wrapper);
        return orderDetailsList;
    }

    @Override
    public Integer getOrderNumber() {
        List<OrderFrom> orderFroms = orderFromMapper.selectList(null);
        return orderFroms.size();
    }

    @Override
    public Float getZumPrice() {
        EntityWrapper<OrderFrom> wrapper = new EntityWrapper<>();
        wrapper.ne("status", "退货中");
        wrapper.ne("status", "退货成功");
        wrapper.ne("status", "未付款");
        List<OrderFrom> orderFroms = orderFromMapper.selectList(wrapper);
        Float price = Float.valueOf(0);
        for (OrderFrom orderFrom : orderFroms) {
            price = price + orderFrom.getPrice();
        }
        return price;
    }

}
